package com.echoesnet.echoesshortvideo.Activities;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.request.RequestOptions;
import com.echoesnet.echoesshortvideo.AppController;
import com.echoesnet.echoesshortvideo.Beans.UserBean;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CdnUtils.CdnHelper;
import com.echoesnet.echoesshortvideo.Utils.CdnUtils.IOnCdnFeedbackListener;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.GlideRoundTransform;
import com.echoesnet.echoesshortvideo.Utils.Image.GlideApp;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.View.MaxByteLengthEditText;
import com.echoesnet.echoesshortvideo.ViewModels.StepRegisterViewModel;
import com.orhanobut.logger.Logger;
import com.soundcloud.android.crop.Crop;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.picker.DateTimePicker;
import cn.qqtheme.framework.widget.WheelView;
import me.iwf.photopicker.PhotoPicker;

public class MakeUserInfo extends BaseActivity
{
    private static final String TAG = MakeUserInfo.class.getSimpleName();
    @BindView(R.id.headImage)
    ImageView headImage;
    @BindView(R.id.tvNickName)
    MaxByteLengthEditText tvNickName;
    @BindView(R.id.tvDate)
    TextView tvDate;
    @BindView(R.id.tvMan)
    TextView tvMan;
    @BindView(R.id.tvWoMan)
    TextView tvWoMan;
    @BindView(R.id.nextOk)
    ImageView nextOk;
    private StepRegisterViewModel lModel;
    private String sex = "";
    private String headImgUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_make_userinfo);
        ButterKnife.bind(this);

        lModel = new StepRegisterViewModel();
        lModel.getLiveData().observe(this, new Observer<String>()
        {
            @Override
            public void onChanged(@Nullable String type)
            {
                if (type == null)
                    return;
                Toast.makeText(getApplicationContext(), "完善资料成功", Toast.LENGTH_SHORT).show();
                finish();
            }
        });

        tvNickName.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                updateBtn();
            }

            @Override
            public void afterTextChanged(Editable s)
            {

            }
        });
        //10个字 20个字母限制
        tvNickName.setMaxByteLength(20);
        nextOk.setClickable(false);
        Selection.setSelection(tvNickName.getText(), tvNickName.getText().length());
    }

    private void updateBtn()
    {
        String name = tvNickName.getText().toString().trim();
        if (!TextUtils.isEmpty(name) || !TextUtils.isEmpty(birthDate) || !TextUtils.isEmpty(headImgUrl) || !sex.equals(""))
        {
            if (!nextOk.isClickable())
            {
                nextOk.setClickable(true);
                nextOk.setAlpha(1f);
            }
        }
        else
        {
            if (nextOk.isClickable())
            {
                nextOk.setClickable(false);
                nextOk.setAlpha(0.5f);
            }

        }



    }

    @OnClick({R.id.cancle, R.id.headImage, R.id.tvDate, R.id.tvMan, R.id.tvWoMan, R.id.nextOk})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.cancle:

                finish();
                break;
            case R.id.headImage:
                toPhotoFromGallery();
                break;
            case R.id.tvDate:
                setNewBirthdayPicker(tvDate);
                break;
            case R.id.tvMan:
                sex = "1";
                tvMan.setAlpha(1f);
                tvWoMan.setAlpha(0.5f);
                updateBtn();
                break;
            case R.id.tvWoMan:
                sex = "0";
                tvMan.setAlpha(0.5f);
                tvWoMan.setAlpha(1f);
                updateBtn();
                break;
            case R.id.nextOk:
                UserBean user = new UserBean();
                user.setNickname(tvNickName.getText().toString().trim());
                user.setSex(sex);
                user.setHeadPic(headImgUrl);
                user.setBirthday(tvDate.getText().toString().trim().contains("-") ? tvDate.getText().toString().trim() : "");
                lModel.makeUserInfo(user);
                break;
        }
    }

    /**
     * 生日选择器
     */
    private void setNewBirthdayPicker(final TextView birth)
    {
        int year = Calendar.getInstance().get(Calendar.YEAR) - 99;
        int month = 3;
        int day = 3;

        String[] text = birth.getText().toString().split("-");
        if (text.length == 3)
        {
            try
            {
                if (Integer.parseInt(text[0]) >= year)
                    year = Integer.parseInt(text[0]);

                if (Integer.parseInt(text[0]) > Calendar.getInstance().get(Calendar.YEAR) - 10)
                    year = Calendar.getInstance().get(Calendar.YEAR) - 10;

                month = Integer.parseInt(text[1]);
                day = Integer.parseInt(text[2]);
            } catch (NumberFormatException e)
            {
                e.printStackTrace();
            }
        }

        DatePicker picker = new DatePicker(this, DateTimePicker.YEAR_MONTH_DAY);
        picker.setCycleDisable(true);
        picker.setDividerVisible(true);
        picker.setTopLineVisible(false);
        picker.setShadowVisible(false);
        picker.setTitleText("选择生日");
        picker.setTitleTextSize(14);
        picker.setTitleTextColor(ContextCompat.getColor(this, R.color.C0321));
        picker.setTitleTextColor(ContextCompat.getColor(this, R.color.C0311));
        picker.setTitleTextColor(ContextCompat.getColor(this, R.color.C0311));
        picker.setTopLineVisible(false);
        picker.setRangeStart(Calendar.getInstance().get(Calendar.YEAR) - 99, 1, 1);
        picker.setRangeEnd(Calendar.getInstance().get(Calendar.YEAR) - 10, Calendar.getInstance().get(Calendar.MONTH) + 1, Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        picker.setSelectedItem(year, month, day);
        WheelView.DividerConfig config1 = new WheelView.DividerConfig();
        config1.setColor(0xFF33B5E5);//线颜色
        config1.setAlpha(140);//线透明度
        config1.setRatio((float) (1.0));//线比率
        picker.setDividerConfig(config1);

        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener()
        {
            @Override
            public void onDatePicked(String year, String month, String day)
            {

                birth.setText(year + "-" + month + "-" + day);
                birthDate = year + "-" + month + "-" + day;
                updateBtn();
            }
        });
        picker.show();
    }

    private String birthDate = "";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent result)
    {
        switch (requestCode)
        {
            case Crop.REQUEST_PICK:
                if (resultCode == RESULT_OK)
                {
                    ArrayList<String> mResults = result.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                    Logger.t(TAG).d("图片地址：" + mResults.get(0));
                    beginCrop(Uri.fromFile(new File(mResults.get(0))));
                }
                break;
            case CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE:
                handleCrop(resultCode, result);
                break;
        }
    }

    private void beginCrop(Uri source)
    {
        CropImage.activity(source)
                .setGuidelines(CropImageView.Guidelines.ON)
                .setCropShape(CropImageView.CropShape.OVAL)
                .setAspectRatio(1, 1)
                .start(this);
    }

    private void handleCrop(int resultCode, Intent result)
    {
        if (resultCode == RESULT_OK)
        {
            CropImage.ActivityResult cropResult = CropImage.getActivityResult(result);
            uploadHeadImg(cropResult.getUri());
        } else if (resultCode == Crop.RESULT_ERROR)
        {
            String error = Crop.getError(result).getMessage();
            Logger.t(TAG).d("拍照返回错误信息--> " + error);
            if (TextUtils.isEmpty(error))
            {
                ToastUtils.showShort("照片裁剪失败");
            } else if (error.toLowerCase().contains("gif"))
            {
                ToastUtils.showShort("不能使用GIF图片");
            } else
            {
                ToastUtils.showShort(error);
            }
        }
    }

    private void uploadHeadImg(final Uri inputUri)
    {
        String fileKeyName = CdnHelper.userImage + UUID.randomUUID().toString().substring(0, 8) + ".jpg";
        CdnHelper.getInstance().setOnCdnFeedbackListener(new CdnFeedbackListener(this, inputUri));
        //  headImage.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_circle_c0412_bg));
        File file = new File(inputUri.getPath());
        Logger.t(TAG).d("PATH:" + inputUri.getPath() + "文件是否存在：" + file.exists());
        CdnHelper.getInstance().putFile(file, "img", fileKeyName, 0);
    }


    private static class CdnFeedbackListener implements IOnCdnFeedbackListener
    {
        private final WeakReference<MakeUserInfo> mActRef;
        private Uri imgUri;

        private CdnFeedbackListener(MakeUserInfo mAct, Uri imgUri)
        {
            this.mActRef = new WeakReference<MakeUserInfo>(mAct);
            this.imgUri = imgUri;
        }

        @Override
        public void onSuccess(JSONObject response, File file, String fileKeyName, int uploadOrder)
        {
            final MakeUserInfo cAct = mActRef.get();
            if (cAct != null)
            {
                Logger.t(TAG).d("成功：" + response.toString());
                GlideApp.with(AppController.getInstance())
                        .asBitmap()
                        .load(imgUri)
                        .apply(RequestOptions.bitmapTransform(new GlideRoundTransform(AppController.getInstance(), 360)))
                        .into(cAct.headImage);
                cAct.headImgUrl = CdnHelper.CDN_ORIGINAL_SITE + fileKeyName;
                mActRef.get().updateBtn();
            }
        }

        @Override
        public void onProcess(long len)
        {

        }

        @Override
        public void onFail(JSONObject response, File file)
        {
            final MakeUserInfo cAct = mActRef.get();
            if (cAct != null)
            {
                Logger.t(cAct.TAG).d("错误：" + response.toString());
            }
        }
    }

    /**
     * 从相机获取图片
     */
    private void toTakePhotoFromCamera()
    {
        boolean isCameraPermissions = CommonUtils.cameraIsCanUse();
        if (isCameraPermissions)
        {
            File storageDir = this.getExternalCacheDir();
            File image = new File(storageDir, "TempImage.jpg");
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (openCameraIntent.resolveActivity(this.getPackageManager()) != null)
            {
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(this, "com.echoesnet.eatandmeet.provider", image));
                startActivityForResult(openCameraIntent, 1);
            }
        } else
        {
            ToastUtils.showShort("请打开相机功能");
        }
    }

    /**
     * 从相册获取图片
     */
    private void toPhotoFromGallery()
    {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setPreviewEnabled(true)
                .setShowCamera(true)
                .setShowGif(false)
                .start(this, Crop.REQUEST_PICK);
    }
}